using AutoMapper;
using Domain;
using ErrorCode;
using Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using RabbitTraceability.Api.Applications.Command;
using RabbitTraceability.Api.Dtos.Response;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace RabbitTraceability.Api.Applications.CommandHandler
{
    /// <summary>
    /// 查询保健信息命令处理程序
    /// </summary>
    public class QueryHealthCareInfoCommandHandler : IRequestHandler<QueryHealthCareInfoCommand, ApiResult<HealthCareInfoResponseDto>>
    {
        private readonly IRepository<HealthCareInfo> _healthCareRepository;
        private readonly IRepository<TraceabilityInfo> _traceabilityRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<QueryHealthCareInfoCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="healthCareRepository">保健信息仓储</param>
        /// <param name="traceabilityRepository">溯源信息仓储</param>
        /// <param name="mapper">映射器</param>
        /// <param name="logger">日志记录器</param>
        public QueryHealthCareInfoCommandHandler(
            IRepository<HealthCareInfo> healthCareRepository,
            IRepository<TraceabilityInfo> traceabilityRepository,
            IMapper mapper,
            ILogger<QueryHealthCareInfoCommandHandler> logger)
        {
            _healthCareRepository = healthCareRepository;
            _traceabilityRepository = traceabilityRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理查询保健信息命令
        /// </summary>
        /// <param name="request">请求命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>保健信息</returns>
        public async Task<ApiResult<HealthCareInfoResponseDto>> Handle(QueryHealthCareInfoCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("查询保健信息，生产批次：{ProductionBatch}", request.ProductionBatch);

                // 参数验证
                if (string.IsNullOrWhiteSpace(request.ProductionBatch))
                {
                    _logger.LogWarning("生产批次不能为空");
                    return ApiResult<HealthCareInfoResponseDto>.BadRequest("生产批次不能为空");
                }

                // 首先验证溯源信息是否存在且未被删除
                var traceabilityInfo = await _traceabilityRepository.GetAll()
                    .FirstOrDefaultAsync(t => t.ProductionBatch == request.ProductionBatch && !t.IsDeleted, cancellationToken);

                if (traceabilityInfo == null)
                {
                    _logger.LogWarning("未找到对应的溯源信息，生产批次：{ProductionBatch}", request.ProductionBatch);
                    return ApiResult<HealthCareInfoResponseDto>.NotExists($"未找到生产批次为 {request.ProductionBatch} 的溯源信息");
                }

                // 查询保健信息
                var healthCareInfo = await _healthCareRepository.GetAll()
                    .FirstOrDefaultAsync(h => h.ProductionBatch == request.ProductionBatch && !h.IsDeleted, cancellationToken);

                if (healthCareInfo == null)
                {
                    _logger.LogWarning("未找到对应的保健信息，生产批次：{ProductionBatch}", request.ProductionBatch);
                    return ApiResult<HealthCareInfoResponseDto>.NotExists($"未找到生产批次为 {request.ProductionBatch} 的保健信息");
                }

                // 映射到响应DTO
                var responseDto = _mapper.Map<HealthCareInfoResponseDto>(healthCareInfo);

                _logger.LogInformation("成功查询到保健信息，保健编号：{HealthCareId}，生产批次：{ProductionBatch}", 
                    healthCareInfo.HealthCareId, request.ProductionBatch);

                return ApiResult<HealthCareInfoResponseDto>.SuccessWithData(responseDto, "查询保健信息成功");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询保健信息时发生异常，生产批次：{ProductionBatch}", request.ProductionBatch);
                return ApiResult<HealthCareInfoResponseDto>.ServerError("查询保健信息失败");
            }
        }
    }
} 